import datetime
import csv
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from django.shortcuts import render
import requests
import re
import json
# Create your views here.


# 设置cq_http的地址
cq_http_link = 'http://127.0.0.1:2333/'

# 设置大群群号
group_id = 123456


def is_chinese(string):
    """
    检查整个字符串是否包含中文
    :param string: 需要检查的字符串
    :return: bool
    """
    for ch in string:
        if u'\u4e00' <= ch <= u'\u9fff':
            return True

    return False


# Q群自动踢人部分
def kick_off(request):
    global cq_http_link
    global group_id
    q_card = request.GET.get('q_card')
    q_card_list = request.GET.get('q_card_list')
    print(q_card)
    if q_card is None and q_card_list is None:
        data = {
            'code': 400,
            'msg': 'Bad Request',
            'info': '参数错误。q_card参数缺失。',
        }
    else:
        if q_card_list:
            q_card_list = q_card_list[1:-1].split(',')

        else:
            q_card_list = [q_card]

        # 获取群成员列表
        data = {
            'group_id': group_id,
            # 不使用缓存，及时更新群名片信息
            'no_cache': 'true',
        }
        member_url = cq_http_link + 'get_group_member_list'
        try:
            member_res = requests.get(url=member_url, params=data)
        except:
            data = {
                'code': 501,
                'msg': 'Robot Server Error',
                'info': '机器人服务器错误，请检查机器人是否正常运行或稍后重试。'
            }
            return JsonResponse(data, json_dumps_params={'ensure_ascii': False})
        # 判断是否为空
        if '群聊不存在' in member_res.text:
            data = {
                'code': 400,
                'msg': 'Server Error',
                'info': '群聊不存在，请检查群号设置和机器人是否已加群！'
            }
            return JsonResponse(data, json_dumps_params={'ensure_ascii': False})
        member_info = member_res.json()['data']
        # 生成群里所有人的card和user_id对应的字典，没有card将放在blank_list里面
        card_id_dict = {}
        blank_list = []
        for info in member_info:
            if info['card']:
                card_id_dict[info['card']] = info['user_id']
            else:
                blank_list.append(info['user_id'])

        # 循环踢人
        log_text = ''
        success_list = []
        failed_list = []
        for q_card in q_card_list:
            if card_id_dict.get(q_card):
                data = {
                    'group_id': group_id,
                    'user_id': card_id_dict[q_card],
                    'reject_add_request': 'false',
                }
                kick_url = cq_http_link + 'set_group_kick'
                res = requests.get(url=kick_url, params=data)
                # 这里的成功只是请求接口成功，但并不代表实际成功，比如管理踢群主会显示权限不足，返回结果仍在成功的列表中
                success_list.append(q_card)
            else:
                failed_list.append(q_card)

        data = {
            'code': 200,
            'msg': 'Success',
            'data': {
                'success_list': success_list,
                'failed_list': failed_list,
                'blank_card_list': blank_list,
            },
        }
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})


# 获取所有群成员信息
def get_info(request):
    global cq_http_link
    global group_id

    # 获取群成员列表
    req_data = {
        'group_id': group_id,
        # 不使用缓存，及时更新群名片信息
        'no_cache': 'true',
    }
    member_url = cq_http_link + 'get_group_member_list'
    try:
        member_res = requests.get(url=member_url, params=req_data)
    except:
        data = {
            'code': 501,
            'msg': 'Robot Server Error',
            'info': '机器人服务器错误，请检查机器人是否正常运行或稍后重试。'
        }
        return JsonResponse(data, json_dumps_params={'ensure_ascii': False})
    # 判断是否为空
    if '群聊不存在' in member_res.text:
        data = {
            'code': 400,
            'msg': 'Server Error',
            'info': '群聊不存在，请检查群号设置和机器人是否已加群！'
        }
        return JsonResponse(data, json_dumps_params={'ensure_ascii': False})
    member_infos = member_res.json()['data']

    member_list = []
    text = f'{cq_http_link}send_msg?group_id={group_id}&message='
    for member in member_infos:
        member_info = {}
        # 判断群名片情况
        if member['role'] == 'owner':
            member_info['info'] = 'Owner'  # 群主
            member_info['direction'] = 'Owner'
            member_info['major_class'] = ''
            member_info['name'] = ''
        elif member['role'] == 'admin':
            member_info['info'] = 'Admin'     # 管理员
            member_info['direction'] = 'Admin'
            member_info['major_class'] = ''
            member_info['name'] = ''
        elif member['user_id'] in [123456, 1234567]:   # 机器人自己的QQ号
            member_info['info'] = 'Robot'
            member_info['direction'] = 'Robot'
            member_info['major_class'] = ''
            member_info['name'] = ''
        elif member['card'] == '':
            member_info['info'] = 'BlankCard'  # 群名片为空
            member_info['direction'] = ''
            member_info['major_class'] = ''
            member_info['name'] = ''
        elif member['card'].startswith('A') and is_chinese(member['card'][1:]):  # 学长学姐的群名片开头为A，且后面是汉字
            member_info['info'] = 'A'
            member_info['direction'] = 'A'
            member_info['major_class'] = ''
            member_info['name'] = member['card'][1:]
            # 这个正则检测不了专业班级简称写不对的
            # 有的同学群名片改不了，应该另外处理
            # 刚开始群名片开头是开发|设计|秘书处，后来改成各方向，只需把下面那一行注释取消然后把另一行注释掉即可
        elif re.findall(r'^(开发|设计|秘书处){1}-[\u4e00-\u9fa5]{1,}[A-z]?[0-9]{1,}-[\u4e00-\u9fa5]{0,}$', member['card']):
        # elif re.findall(r'^(CPU&OS|JAVA|秘书处|全栈|人工智能|设计){1}-[\u4e00-\u9fa5]{1,}[A-z]?[0-9]{1,}-[\u4e00-\u9fa5]{0,}$', member['card']):
            member_info['info'] = 'Success'  # 群名片正则匹配成功
            card_info = member['card'].split('-')
            member_info['direction'] = card_info[0]
            member_info['major_class'] = card_info[1]
            member_info['name'] = card_info[2]
        else:
            member_info['info'] = 'Failure'  # 其它情况均为失败
            member_info['direction'] = ''
            member_info['major_class'] = ''
            member_info['name'] = ''
            # 填写其它基本信息
        # 判断是否为cq请求
        if request.GET.get('cq'):
            # 如果为空或者格式不正确
            if member_info['info'] == 'Failure' or member_info['info'] == 'BlankCard':
                module_text = f'[CQ:at,qq={member["user_id"]}]'
                text = text + module_text
            continue

        member_info['card'] = member['card']
        member_info['join_time'] = member['join_time']
        member_info['last_sent_time'] = member['last_sent_time']
        member_info['nickname'] = member['nickname']
        member_info['sex'] = member['sex']
        member_info['user_id'] = member['user_id']
        # 加入列表
        member_list.append(member_info)

    # 返回CQ请求（生成一键艾特没改对群名片的链接）
    if request.GET.get('cq'):
        return HttpResponse(text)
    # 返回群成员的csv名单
    if request.GET.get('file'):
        file_name = 'group_info' + str(datetime.datetime.now()).replace(' ', '-').replace(':', '-') + '.csv'
        with open(r'./static/group_info/' + file_name, 'w+', encoding='utf8', newline='') as csv_file:
            fieldnames = ['user_id', 'direction', 'name', 'major_class', 'sex', 'nickname', 'card', 'info', 'join_time', 'last_sent_time']
            writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerows(member_list)
        return HttpResponseRedirect('/static/group_info/' + file_name)

    data = {
        'code': 200,
        'msg': 'Success',
        'data': member_list,
    }
    return JsonResponse(data, json_dumps_params={'ensure_ascii': False})

# 以下是机器人收到消息后进行信息处理的功能
from app.robot_plugins import *
# 机器人处理部分
# 接收信息


def request_test(request):
    res = 'Blank'
    bytes_info = request.body
    # 元信息处理
    import json
    text = bytes_info.decode('utf-8')[:-1]
    test_dict = json.loads(text)
    # 判断是否为戳一戳事件
    if test_dict.get('sub_type') == 'poke':
        # 进入戳一戳hitikoto插件
        res = poke_hitokoto(text)
    if test_dict.get('post_type') == 'message':
        if test_dict.get('message_type') == 'group':
            # auto_ban_ad(text)
            # get_red_head(text)
            logo_create(text)
            print(show_group_flash_image(text, mode=3))
            get_random_setu(text)
            game_server_info(text)
        elif test_dict.get('message_type') == 'private':
            tyut_bot(text)
            get_random_setu(text)
            show_flash_image(text)
    elif test_dict.get('post_type') == 'notice':
        group_in_out_plugin(text)
    return HttpResponse(res)
